(function(D){
    var addTerm, autocompleteTerms, domInput;

    D.terms = {};
    addTerm = function(item){
        var classLabel, encodedClassLabel, termLabel, encodedTermLabel, timestamp, classId, makeTerm; 

        makeTerm = function(){
            timestamp += 1;
            D.request("addTerm.txt",
                {
                    classId: classId,
                    termLabel: encodedTermLabel,
                    user: D.userName,
                    timestamp: timestamp
                }, null, true);
            D.terms[item]={
                id: 'http://desanti.org/terms/'+timestamp,
                label: termLabel,
                class: classId,
                classLabel: classLabel,
                classNum: 'term'+classLabel.replace(/.*\//,'')
            };
            autocompleteTerms();
        }

        if(!confirm("ajouter le terme " + item + " ?")) return;
        split = item.split(":");
        if(split.length != 2){alert("terme mal nommé"); return;}
        classLabel = D.capitaliseFirstLetter(split[0].toLowerCase());
        termLabel = split[1].toLowerCase();
        encodedClassLabel = encodeURIComponent(classLabel);
        encodedTermLabel = encodeURIComponent(termLabel);
        timestamp = D.timestamp();
        $.each(D.terms, function(label, t){
            if(t.classLabel === classLabel){
                classId = t.class;
                return false;
            }
        });
        if(!classId){
            classId = 'http://desanti.org/classes/'+timestamp;
            D.request("addClass.txt",
                {
                    classLabel: encodedClassLabel,
                    classId: classId,
                    user: D.userName,
                    timestamp: timestamp
                },makeTerm, true);
        }else{ makeTerm(); }
    }

    autocompleteTerms = function(){
        var autocompleteList = [];

        $.each(D.terms, function(item){
            autocompleteList.push(item);
        });
        D.autocomplete(autocompleteList, 
            domInput,
            function(item){
                if(!D.terms[item]){
                    addTerm(item);
                }
            });
    }

    D.initTerms = function(inputId){
        domInput = document.getElementById(inputId);
        D.request("get_terms.txt",{},function(results){
            $.each(results, function(i,r){
                var classLabel = decodeURIComponent(r.cLabel.value),
                    termLabel = decodeURIComponent(r.tLabel.value);
                D.terms[classLabel+':'+termLabel]={
                    id: r.t.value,
                    label: termLabel,
                    class: r.c.value,
                    classLabel: classLabel,
                    classNum: 'term'+r.c.value.replace(/.*\//,'')
                };
            });
            autocompleteTerms();
        });
    }
})(DESANTI);
